#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask import Flask
from flask_jwt_extended import JWTManager

from config import config
from models import db, migrate
from api import api_bp
from auth import auth_bp


def create_app(config_name='default'):
    """创建Flask应用实例"""
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    
    # 初始化扩展
    db.init_app(app)
    migrate.init_app(app, db)
    jwt = JWTManager(app)
    
    # JWT加载用户回调
    @jwt.user_lookup_loader
    def user_lookup_callback(_jwt_header, jwt_data):
        from flask import g
        from models import User
        
        identity = jwt_data["sub"]
        g.current_user = User.query.filter_by(username=identity).first()
        return g.current_user
    
    # 注册蓝图
    app.register_blueprint(api_bp, url_prefix='/api')
    app.register_blueprint(auth_bp, url_prefix='/auth')
    
    return app


if __name__ == '__main__':
    app = create_app()
    app.run(host='0.0.0.0', port=5000, debug=True)